﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Data;
using System.Configuration;
using System.Data.OleDb;
using System.Diagnostics;
using System.IO;
using System.Web;
using System.Threading;
using System.Data.SqlClient;
using XMK.Tadong.Data;

namespace XMK.Tadong.StructuredData_IntoDb.Data
{
    public class StandardService
    {


        /// <summary>
        /// 通过井号和开始时间判断数据是否存在
        /// </summary>
        /// <param name="wellid"></param>
        /// <param name="kssj"></param>
        /// <returns></returns>
        public bool Exists_idDate(string wellid, DateTime kssj)
        {

            string StrSql = "select count(1) from dict_table where WELLID='" + wellid + "' and KSSJ= to_date( '" + kssj + "','yyyy-MM-dd HH24:mi:ss ')";
            DataTable dt = DbHelperOra.Query_Table(StrSql);
            int i = Convert.ToInt32(dt.Rows[0][0].ToString());
            if (i != 0) return false;
            return true;
        }
        /// <summary>
        /// 通过井号和检测日期判断数据是否存在
        /// </summary>
        /// <param name="wellid"></param>
        /// <param name="jcrq"></param>
        /// <returns></returns>
        public bool Exists_idJCRQ(string wellid, DateTime jcrq)
        {

            string StrSql = "select count(1) from dict_table where WELLID='" + wellid + "' and JCRQ= to_date( '" + jcrq + "','yyyy-MM-dd HH24:mi:ss ')";
            DataTable dt = DbHelperOra.Query_Table(StrSql);
            int i = Convert.ToInt32(dt.Rows[0][0].ToString());
            if (i != 0) return false;
            return true;
        }

        /// <summary>
        /// 待采集数据表
        /// </summary>
        /// <returns></returns>
        public static DataTable GetInputTables()
        {
            OraDataService ods = new OraDataService();

            string StrSql = "select t.table_name,t.table_name_cn from jrsc_table t order by t.xssx";

            DataTable dt = ods.GetTable(StrSql);

            return dt;
        }

        /// <summary>
        /// 获得某个表的EXCEL模板文件名,现在改为表代码+“.xls”
        /// </summary>
        /// <param name="BDM">表代码</param>
        /// <returns>EXCEL模板文件名</returns>
        public static string GetInputTableExcelTemplate(string BDM)
        {
            //OraDataService ods = new OraDataService();
            //string StrSql = "select exceltemplate from jrsc_table where table_name='" + BDM + "'";
            //object o = ods.GetValue(StrSql);
            //if ((o != null) && (!string.IsNullOrEmpty(o.ToString())))
            //    return o.ToString();
            //else
            //    return "";
            return BDM.Trim().ToString() + ".xls";
        }



        /// <summary>
        /// 获得空的待采集表
        /// </summary>
        /// <param name="BDM">表代码</param>
        /// <returns></returns>
        public static DataTable GetInputTableNoData(string BDM)
        {
            #region 代码实现
            //获取字段项列表
            string FieldList = GetInputFieldsList(BDM);

            //如果数据为空
            if (FieldList == "")
                return null;
            else
            {
                OraDataService ods = new OraDataService();

                string StrSql = "select  " + FieldList + "  from " + BDM + "  where 1=2";

                DataTable dt = ods.GetTable(StrSql);

                return dt;
            }
            #endregion 代码实现
        }



        /// <summary>
        /// 待采集表原始数据
        /// </summary>
        /// <param name="BDM"></param>
        /// <returns></returns>
        public static DataTable GetInputTableOraginData(string BDM)
        {
            //获取字段项列表
            string FieldList = GetInputFieldsList(BDM);

            //如果数据为空
            if (FieldList == "")
                return null;
            else
            {
                OraDataService ods = new OraDataService();

                string StrSql = "select  " + FieldList + "  from " + BDM;

                DataTable dt = ods.GetTable(StrSql);

                return dt;
            }
        }

        /// <summary>
        /// 20100125张玉峰添加
        /// 在通用录入页面中，在有过滤条件下查询数据时，就调用本函数。
        /// 例如我要更新的是某个项目相关的数据，而不是整表数据。
        /// 参数p_Filter是一个HASHTABLE，例如当前更新的是项目ID=1的数据，p_Filter中就存储key="ID_PROJECT",value="1"
        /// </summary>
        /// <param name="BDM"></param>
        /// <param name="p_Filter"></param>
        /// <returns></returns>
        public static DataTable GetInputTableOraginData_Filter(string BDM, Hashtable p_Filter)
        {
            //获取字段项列表
            string FieldList = GetInputFieldsList(BDM);

            //如果数据为空
            if (FieldList == "")
                return null;
            else
            {
                OraDataService ods = new OraDataService();
                string strWhere = "";
                if ((p_Filter != null) && (p_Filter.Count > 0))
                {

                    foreach (object key in p_Filter.Keys)
                    {
                        strWhere += key.ToString() + "='" + p_Filter[key.ToString()].ToString() + "' AND ";
                    }
                    if (strWhere.Length > 0)
                    {
                        strWhere = " where " + strWhere.Substring(0, strWhere.Length - 4);
                    }

                }
                string StrSql = "select  " + FieldList + "  from " + BDM + strWhere;

                DataTable dt = ods.GetTable(StrSql);

                return dt;
            }
        }

        /// <summary>
        /// 待采集表字段项
        /// </summary>
        /// <param name="BDM"></param>
        /// <returns></returns>
        public static DataTable GetInputFields(string BDM)
        {
            OraDataService ods = new OraDataService();

            //string StrSql = "select f.id,f.fldname,f.fldname_cn,f.fldtype,f.xskd,f.sjy,f.fzdid,f.ispkey,f.sfxs,f.fldwidth,f.isnull,f.sfjs,f.columnwidth,f.isuq,f.POP_WIN from jrsc_field f where f.table_name='" + BDM + "'  order by f.ispkey desc,f.xsxh";
            string StrSql = "select * from dict_col WHERE TABLE_ID =" +
                "(SELECT TABLE_ID FROM dict_table WHERE table_code='" + BDM.Trim().ToString() + "') order by field_id asc";

            DataTable dt = ods.GetTable(StrSql);

            return dt;
        }
        /// <summary>
        /// 获取字段项列表
        /// </summary>
        /// <param name="BDM"></param>
        /// <returns></returns>
        public static string GetInputFieldsList(string BDM)
        {
            string FieldList = "";
            //获取字段项列表
            DataTable FieldData = GetInputFields(BDM);
            //如果数据为空
            if (FieldData != null && FieldData.Rows.Count != 0)
            {
                for (int k = 0; k < FieldData.Rows.Count; k++)
                {
                    if (FieldList == "")
                    {
                        //FieldList = FieldData.Rows[k]["fldname"].ToString();
                        FieldList = FieldData.Rows[k]["FIELD_CODE"].ToString();
                    }
                    else
                    {
                        //FieldList = FieldList + "," + FieldData.Rows[k]["fldname"].ToString();
                        FieldList = FieldList + "," + FieldData.Rows[k]["FIELD_CODE"].ToString();
                    }
                }
            }
            return FieldList;
        }
        /// <summary>
        /// 获取字段项列表
        /// </summary>
        /// <param name="BDM">表代码</param>
        /// <param name="IsOnlyShowFields">是否只获得显示列</param>
        /// <returns></returns>
        public static string GetInputFieldsList(string BDM, bool IsOnlyShowFields)
        {
            string FieldList = "";
            //获取字段项列表
            DataTable FieldData = GetInputFields(BDM);
            //如果数据为空
            if (FieldData != null && FieldData.Rows.Count != 0)
            {
                if (IsOnlyShowFields == false)
                {
                    for (int k = 0; k < FieldData.Rows.Count; k++)
                    {
                        if (FieldData.Rows[k]["FIELD_SHOW"].ToString().Trim() == "1")
                        {
                            if (FieldList == "")
                            {
                                FieldList = FieldData.Rows[k]["FIELD_CODE"].ToString();
                            }
                            else
                            {
                                FieldList = FieldList + "," + FieldData.Rows[k]["FIELD_CODE"].ToString();
                            }
                        }
                    }
                }
                else
                {
                    for (int k = 0; k < FieldData.Rows.Count; k++)
                    {
                        if (FieldList == "")
                        {
                            FieldList = FieldData.Rows[k]["FIELD_CODE"].ToString();
                        }
                        else
                        {
                            FieldList = FieldList + "," + FieldData.Rows[k]["FIELD_CODE"].ToString();
                        }
                    }
                }
            }
            return FieldList;
        }
        /// <summary>
        /// 字段项数据源
        /// </summary>
        /// <param name="SJY"></param>
        /// <returns></returns>
        public static DataTable GetInputFieldDataSource(string SJY)
        {
            OraDataService ods = new OraDataService();

            DataTable dt = ods.GetTable(SJY);

            return dt;
        }
        /// <summary>
        /// 采集数据更新到数据库
        /// </summary>
        /// <param name="UpdateTable"></param>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public static bool UpdateTable(DataTable UpdateTable, string TableName)
        {
            OraDataService ods = new OraDataService();

            return ods.UpdateTable(UpdateTable, TableName);
        }

        /// <summary>
        /// 20100125张玉峰添加
        /// 在通用录入页面中，在有过滤条件下更新数据时，就调用本函数。
        /// 参数p_Filter是一个HASHTABLE，例如当前更新的是项目ID=1的数据，p_Filter中就存储key="ID_PROJECT",value="1",
        /// 在保存到数据库前，把每条新增记录的ID_PROJECT字段赋值为"1"
        /// 
        /// 如果该表的主键是一个类似于SQLSERVER的自增列，就用参数p_AutoColumn传进来
        /// </summary>
        /// <param name="UpdateTable"></param>
        /// <param name="TableName"></param>
        /// <param name="p_Filter"></param>
        /// <param name="p_AutoColumn"></param>
        /// <returns></returns>
        public static bool UpdateTable_Filter(DataTable UpdateTable, string TableName, Hashtable p_Filter, string p_AutoColumn)
        {
            #region 代码实现
            OraDataService ods = new OraDataService();
            string strSql = "";
            //if (!string.IsNullOrEmpty(p_AutoColumn))//处理自增列，在全表范围内查询出最大值，顺序加1(因为在数据库中已经设置了自增了所有在程序中就不在需要这段代码了zxf)
            //{
            //    int max = 0;
            //    strSql = "select max(" + p_AutoColumn + ")  from " + TableName;
            //    string strID = ods.GetValue(strSql).ToString();
            //    if (!string.IsNullOrEmpty(strID))
            //    {
            //        max = Convert.ToInt32(strID);
            //    }

            //    DataRow[] arrRows1 = UpdateTable.Select(p_AutoColumn + " is NULL");
            //    foreach (DataRow dr in arrRows1)
            //    {
            //        dr.BeginEdit();
            //        dr[p_AutoColumn] = ++max;
            //        dr.EndEdit();
            //    }
            //}

            if ((p_Filter != null) && (p_Filter.Count > 0))//例如：新增记录没有所属项目的值（因为录入界面不提供），这里为每条记录赋所属项目的值
            {
                string strWhere = "";
                foreach (object key in p_Filter.Keys)
                {
                    strWhere += key.ToString() + " is null  or ";
                }
                strWhere = strWhere.Substring(0, strWhere.Length - 4);

                DataRow[] arrRows2 = UpdateTable.Select(strWhere);
                foreach (DataRow dr in arrRows2)
                {
                    dr.BeginEdit();
                    foreach (object key in p_Filter.Keys)
                    {
                        dr[key.ToString()] = p_Filter[key.ToString()].ToString();
                    }
                    dr.EndEdit();
                }

            }

            //return ods.UpdateTable(UpdateTable, TableName);
            return ods.UpdateTable2Key(UpdateTable, TableName);
            #endregion 代码实现
        }

        /// <summary>
        /// 更新表记录
        /// </summary>
        /// <param name="UpdateTable">需要更新的表数据</param>
        /// <param name="TableName">表代码</param>
        /// <param name="p_Filter">过滤字段</param>
        /// <param name="p_AutoColumn">自增列</param>
        /// <param name="IsIgnoreKeyConflict">是否过滤主键冲突</param>
        /// <returns>成功返回true，失败返回false</returns>
        public static bool UpdateTable_Filter(DataTable UpdateTable, string TableName, Hashtable p_Filter, string p_AutoColumn, bool IsIgnoreKeyConflict)
        {
            #region 代码实现
            OraDataService ods = new OraDataService();
            string strSql = "";

            if ((p_Filter != null) && (p_Filter.Count > 0))//例如：新增记录没有所属项目的值（因为录入界面不提供），这里为每条记录赋所属项目的值
            {
                string strWhere = "";
                foreach (object key in p_Filter.Keys)
                {
                    strWhere += key.ToString() + " is null  or ";
                }
                strWhere = strWhere.Substring(0, strWhere.Length - 4);

                DataRow[] arrRows2 = UpdateTable.Select(strWhere);
                foreach (DataRow dr in arrRows2)
                {
                    dr.BeginEdit();
                    foreach (object key in p_Filter.Keys)
                    {
                        dr[key.ToString()] = p_Filter[key.ToString()].ToString();
                    }
                    dr.EndEdit();
                }

            }
            return ods.UpdateTable2Key(UpdateTable, TableName, IsIgnoreKeyConflict);
            #endregion 代码实现
        }

        #region
        //public static bool UpdateTable_Filter(DataTable UpdateTableCopy, DataTable UpdateTable, string TableName, Hashtable p_Filter, string p_AutoColumn)
        //{
        //    #region 代码实现
        //    OraDataService ods = new OraDataService();
        //    string strSql = "";
        //    if (!string.IsNullOrEmpty(p_AutoColumn))//处理自增列，在全表范围内查询出最大值，顺序加1
        //    {
        //        int max = 0;
        //        strSql = "select max(" + p_AutoColumn + ")  from " + TableName;
        //        string strID = ods.GetValue(strSql).ToString();
        //        if (!string.IsNullOrEmpty(strID))
        //        {
        //            max = Convert.ToInt32(strID);
        //        }

        //        DataRow[] arrRows1 = UpdateTableCopy.Select(p_AutoColumn + " is NULL");
        //        foreach (DataRow dr in arrRows1)
        //        {
        //            dr.BeginEdit();
        //            dr[p_AutoColumn] = ++max;
        //            dr.EndEdit();
        //        }
        //    }

        //    if ((p_Filter != null) && (p_Filter.Count > 0))//例如：新增记录没有所属项目的值（因为录入界面不提供），这里为每条记录赋所属项目的值
        //    {
        //        string strWhere = "";
        //        foreach (object key in p_Filter.Keys)
        //        {
        //            strWhere += key.ToString() + " is null  or ";
        //        }
        //        strWhere = strWhere.Substring(0, strWhere.Length - 4);

        //        DataRow[] arrRows2 = UpdateTableCopy.Select(strWhere);
        //        foreach (DataRow dr in arrRows2)
        //        {
        //            dr.BeginEdit();
        //            foreach (object key in p_Filter.Keys)
        //            {
        //                dr[key.ToString()] = p_Filter[key.ToString()].ToString();
        //            }
        //            dr.EndEdit();
        //        }

        //    }

        //    if (!string.IsNullOrEmpty(p_AutoColumn))//处理自增列，在全表范围内查询出最大值，顺序加1
        //    {
        //        int max = 0;
        //        strSql = "select max(" + p_AutoColumn + ")  from " + TableName;
        //        string strID = ods.GetValue(strSql).ToString();
        //        if (!string.IsNullOrEmpty(strID))
        //        {
        //            max = Convert.ToInt32(strID);
        //        }

        //        DataRow[] arrRows1 = UpdateTable.Select(p_AutoColumn + " is NULL");
        //        foreach (DataRow dr in arrRows1)
        //        {
        //            dr.BeginEdit();
        //            dr[p_AutoColumn] = ++max;
        //            dr.EndEdit();
        //        }
        //    }

        //    if ((p_Filter != null) && (p_Filter.Count > 0))//例如：新增记录没有所属项目的值（因为录入界面不提供），这里为每条记录赋所属项目的值
        //    {
        //        string strWhere = "";
        //        foreach (object key in p_Filter.Keys)
        //        {
        //            strWhere += key.ToString() + " is null  or ";
        //        }
        //        strWhere = strWhere.Substring(0, strWhere.Length - 4);

        //        DataRow[] arrRows2 = UpdateTable.Select(strWhere);
        //        foreach (DataRow dr in arrRows2)
        //        {
        //            dr.BeginEdit();
        //            foreach (object key in p_Filter.Keys)
        //            {
        //                dr[key.ToString()] = p_Filter[key.ToString()].ToString();
        //            }
        //            dr.EndEdit();
        //        }

        //    }

        //    return ods.UpdateTable(UpdateTableCopy, UpdateTable, TableName);
        //    #endregion 代码实现
        //}
        #endregion

        /// <summary>
        /// 采集数据更新到数据库
        /// </summary>
        /// <param name="UpdateTable"></param>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public static bool UpdateTable(DataTable UpdateTable, string UpdateField, string TableName)
        {
            OraDataService ods = new OraDataService();

            return ods.UpdateTable(UpdateTable, UpdateField, TableName);
        }
        /// <summary>
        /// 字段计算参数项
        /// </summary>
        /// <param name="FieldID"></param>
        /// <returns></returns>
        public static DataTable GetDataFieldFactor(string FieldID)
        {
            OraDataService ods = new OraDataService();

            string StrSql = "select id,zbdm,zblx,zbsjy,zbmc,zbxh,zbdw,zbfw from dev_datafactor  where zdid='" + FieldID + "' order by zbxh";

            DataTable dt = ods.GetTable(StrSql);

            return dt;
        }
        /// <summary>
        /// 解码
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string Dcode(string password)
        {
            string pass = "";
            for (int i = 0; i < password.Length; i++)
            {
                pass = pass + (char)(password[i] - 10 + i * 2);
            }
            return pass;
        }
        /// <summary>
        /// 字段计算公式
        /// </summary>
        /// <param name="FieldID"></param>
        /// <returns></returns>
        public static string GetFormula(string FieldID)
        {
            OraDataService ods = new OraDataService();

            string StrSql = "select gsmc  from dev_dataformula  where zdid='" + FieldID + "'";

            DataTable dt = ods.GetTable(StrSql);

            if (dt == null || dt.Rows.Count == 0)
            {
                return "";
            }
            else
                return dt.Rows[0][0].ToString();
        }
        /// <summary>
        /// 字段计算过程
        /// </summary>
        /// <param name="FieldParameters"></param>
        /// <returns></returns>
        public static string ComunicateDataField(string FieldParameters)
        {
            return "";

            /*
            string[] FieldParameter = FieldParameters.Split('#');
            //获取字段编号
            string FieldID = FieldParameter[0].ToString();
            //获取字段计算参数代码
            string ZBDMS = FieldParameter[1].ToString();
            //获取字段计算参数数值
            string ZBSZS = FieldParameter[2].ToString();

            //获取字段计算公式
            string Expression = StandardService.GetFormula(FieldID);

            if (Expression == "")
                return "";
            else
            {
                //替换公式中的计算参数
                string[] ZBDM = ZBDMS.Split(',');
                string[] ZBSZ = ZBSZS.Split(',');
                for (int i = 0; i < ZBDM.Length; i++)
                {
                    Expression = Expression.Replace(ZBDM[i].ToString(), ZBSZ[i].ToString());
                }
                //根据表达式计算结果
                IServiceContainer MyService = new ServiceContainer();
                ciloci.FormulaEngine.FormulaEngine fe = new ciloci.FormulaEngine.FormulaEngine();//MyService.GetService(typeof(FormulaEngine));
                ciloci.FormulaEngine.Formula f = fe.CreateFormula(Expression);
                f.ResultType = ciloci.FormulaEngine.OperandType.Double;
                object Evaluateresult = f.Evaluate();
                double result = (double)Evaluateresult;//一定要用double类型. 
                return Math.Round(result, 4).ToString();
            }
             */
        }

    }
}
